#!/bin/bash

# Denyhosts版本
Denyhosts_Version=3.0

# 脚本所在路径
ScriptsDir=$(dirname $0)

# Denyhosts配置文件
Denyhost_Config="/etc/denyhosts.conf"

# Denyhosts控制脚本
Denyhosts_CTL="/etc/init.d/denyhosts"

# 释放IP
IP=$2



## 函数定义

# Denyhosts 安装
Install(){
# 下载Denyhosts安装包
if [ ! -f ${ScriptsDir}/denyhosts-${Denyhosts_Version}.tar.gz ];then
    wget https://jaist.dl.sourceforge.net/project/denyhosts/denyhosts/${Denyhosts_Version}/denyhosts-${Denyhosts_Version}.tar.gz --no-check-certificate
fi
# 解压软件包,安装Denyhosts
if [ ! -f ${Denyhost_Config} ];then
    tar -xzf ${ScriptsDir}/denyhosts-${Denyhosts_Version}.tar.gz
    cd ${ScriptsDir}/denyhosts-${Denyhosts_Version}
    /usr/bin/python setup.py install
fi
# 修改配置文件${Denyhost_Config}
if [ -f /var/log/secure ];then
    sed -i 's#SECURE_LOG = /var/log/.*#SECURE_LOG = /var/log/secure#g' ${Denyhost_Config}
elif [ -f /var/log/auth.log ];then
    sed -i 's#SECURE_LOG = /var/log/.*#SECURE_LOG = /var/log/auth.log#g' ${Denyhost_Config}
fi
# 拷贝控制脚本,设置开机启动

## 拷贝控制脚本
if [ ! -f ${Denyhosts_CTL} ];then
    cp -a ${ScriptsDir}/denyhosts-${Denyhosts_Version}/daemon-control-dist ${Denyhosts_CTL}
    sed -i 's#sbin/denyhosts#bin/denyhosts.py#g' ${Denyhosts_CTL}
## 设置开机启动
    chown root ${Denyhosts_CTL}
    chmod 700 ${Denyhosts_CTL}
    chkconfig denyhosts on
fi

# 重启Denyhosts
${Denyhosts_CTL} restart

}

# IP封禁解yy除
Release(){
# 删除/etc/hosts.deny记录
sed -i /${IP}/d /etc/hosts.deny

# 删除日志/var/log/[secure,auth.log]中的记录。
if [ -f /var/log/secure ];then
    sed -i /${IP}/d /var/log/secure 
elif [ -f /var/log/auth.log ];then
    sed -i /${IP}/d /var/log/auth.log 
fi

# 删除denyhosts中的记录
sed -i /${IP}/d /var/lib/denyhosts/*

# 删除防火墙中的记录
iptables -D INPUT --source ${IP} -j DROP &> /dev/null

# 重启Denyhosts
${Denyhosts_CTL} restart
}



# 执行脚本
case $1 in
install)
    # 检查输入的参数个数是否为1，安装脚本只需要一个参数，就是install。
    if [ $# -eq 1 ];then
        Install
    else
	echo -e "\e[1;33mUsage: \e[0m \e[1;32m$(basename $0)\e[0m [install|release] [IP]"
    fi
    exit;;
release)
    # 释放IP脚本，需要两个参数，参数一：功能参数，install-安装，release-IP释放。参数二：IP-要释放的IP地址。判断是否满足参数个数2
    if [ $# -eq 2 ];then
	# 检查IP地址格式。
	echo $2 |grep '[0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}[.][0-9]\{1,3\}' &> /dev/null
	if [ $? -eq 0 ];then
	    Release
	else
	    echo -e "\e[1;31m[ERROR]\e[0m \e[1;32mIP地址格式错误，请输入正确的IP地址\e[0m"
	fi
    else
        echo -e "\e[1;33mUsage: \e[0m \e[1;32m$(basename $0)\e[0m [install|release] [IP]"
    fi
    exit;;
*)
    # 输出脚本使用方法
    echo -e "\e[1;33mUsage: \e[0m \e[1;32m$(basename $0)\e[0m [install|release] [IP]"
    exit;;
esac

